package com.imooc.distributedemo.controller;

import com.imooc.distributedemo.common.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class ZookeeperController {

    @Autowired
    private CuratorFramework client;

    @GetMapping("/zkLock")
    public String zkLock() {
        log.info("我进入了方法");

        try(ZkLock zkLock = new ZkLock()){
            if(zkLock.getLock("order")){
                log.info("我进入了锁");
                Thread.sleep(25000);
            }
        }catch (Exception e){
            log.error("出错了。");
        }
        return "我执行完了";
    }

    @GetMapping("/curatorLock")
    public String curatorLock() {
        log.info("我进入了方法");
        InterProcessMutex lock = new InterProcessMutex(client,"/order");
        try{

            if(lock.acquire(30, TimeUnit.SECONDS)){
                log.info("我进入了锁");
            }
        }catch (Exception e){
            log.error("出错了。");
        }finally {
            try {
                lock.release();
                log.info("我释放了锁");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "我执行完了";
    }
}
